package com.ffalcon.mercury.android.sdk.demo

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson

object SPUtils {
    private const val spName = "rtmpVr"

    fun putValue(context: Context, key: String, value: Any) {
        val sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE)
        val editor = sp.edit()
        when (value) {
            is Boolean -> editor.putBoolean(key, value)
            is Float -> editor.putFloat(key, value)
            is Int -> editor.putInt(key, value)
            is Long -> editor.putLong(key, value)
            is String -> editor.putString(key, value)
            else -> {
                val json = Gson().toJson(value)
                editor.putString(key, json)
            }
        }.apply {
            editor.apply()
        }
    }


    fun getValue(context: Context, key: String, defValue: Any): Any? {
        val sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE)
        return when (defValue) {
            is Boolean -> sp.getBoolean(key, defValue)
            is Float -> sp.getFloat(key, defValue)
            is Int -> sp.getInt(key, defValue)
            is Long -> sp.getLong(key, defValue)
            is String -> sp.getString(key, defValue)
            else -> null
        }
    }

    fun <T> getObjectFromSP(context: Context, key: String, clazz: Class<T>): T? {
        val sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE)
        val json = sp.getString(key, "") ?: return null
        return Gson().fromJson(json, clazz)
    }

    fun clearSP(context: Context) {
        context.getSharedPreferences(spName, Context.MODE_PRIVATE)
            .edit()
            .clear()
            .apply()
    }

    fun removeSP(context: Context, key: String) {
        context.getSharedPreferences(spName, Context.MODE_PRIVATE)
            .edit()
            .remove(key)
            .apply()
    }

    fun getAllSP(context: Context): Map<String, *> {
        return context.getSharedPreferences(spName, Context.MODE_PRIVATE).all
    }
}